package com.shopping.mall.core.module.order.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.base.redis.RedisHeader;
import com.shopping.mall.base.state.OrderState;
import com.shopping.mall.base.util.DateUtils;
import com.shopping.mall.base.util.FileUtils;
import com.shopping.mall.base.util.WrapperUtils;
import com.shopping.mall.core.module.order.entity.Delivery;
import com.shopping.mall.core.module.order.entity.Order;
import com.shopping.mall.core.module.order.entity.OrderDelivery;
import com.shopping.mall.core.module.order.listener.DeliveryListener;
import com.shopping.mall.core.module.order.mapper.OrderMapper;
import com.shopping.mall.core.module.order.service.DeliveryService;
import com.shopping.mall.core.module.order.service.MailService;
import com.shopping.mall.core.module.saleData.service.SaleDataService;
import com.shopping.mall.core.module.specialValue.entity.SpecialValue;
import com.shopping.mall.core.module.specialValue.mapper.SpecialValueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DeliveryServiceImpl implements DeliveryService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SaleDataService saleDataService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SpecialValueMapper specialValueMapper;
    @Autowired
    private MailService mailService;

    @Override
    public Result<Order> setDelivery(OrderDelivery orderDelivery) {
        //是否是第一次发货
        boolean isFirst=false;
        Order order=orderMapper.selectById(orderDelivery.getOrderId());
        if(order.getState()!= OrderState.COPY_SUCCESS.getValue()&&order.getState()!=OrderState.GOOD_HAS_SEND.getValue()){
            return Result.error(ResponseState.ORDER_NOT_MATCH.getValue(), ResponseState.ORDER_NOT_MATCH.getMessage());
        }
        order.setDelivery(JSON.toJSONString(orderDelivery.getDeliveryList()));
        if(order.getState()==OrderState.COPY_SUCCESS.getValue()){
            order.setState(OrderState.GOOD_HAS_SEND.getValue());
            isFirst=true;
        }
        SpecialValue specialValue=specialValueMapper.selectOne(new QueryWrapper<>());
        order.setAutoFinishAt(DateUtils.getTimeAfterDay(specialValue.getOrderAutoFinish()));
        orderMapper.updateById(order);
        if(isFirst){
            saleDataService.delivery(order);
            mailService.sendOrder(order);
        }
        stringRedisTemplate.opsForValue().set(RedisHeader.ORDER_AUTO_FINISH.getHeader()+"__"+order.getId(), String.valueOf(new Date().getTime()),specialValue.getOrderAutoFinish(), TimeUnit.DAYS);
        return Result.OK(order);
    }

    @Override
    public Result<Object> batchSetDelivery(MultipartFile file) {
        if(!FileUtils.isExcel(file.getOriginalFilename())){
            return Result.error(ResponseState.FILE_FORMAT_ERROR.getValue(), ResponseState.FILE_FORMAT_ERROR.getMessage());
        }
        DeliveryListener deliveryListener=new DeliveryListener();
        List<Delivery> deliveries=null;
        try {
            EasyExcel.read(file.getInputStream(), Delivery.class,deliveryListener).sheet().doRead();
            deliveries=deliveryListener.getList();
            System.out.println(deliveries);
        } catch (Exception e) {
            e.printStackTrace();
        }
        batch(deliveries);
        return Result.OK();
    }

    public void batch(List<Delivery> deliveries){
        for(Delivery delivery:deliveries){
            boolean isFirst=false;
            boolean isExist=false;
            List<Delivery> deliveryList=new ArrayList<>();
            Order order= orderMapper.selectOne(WrapperUtils.getQueryWrapper("order_number",delivery.getNumber()));
            if(order.getDelivery()!=null) {
                JSONArray jsonArray = JSONArray.parseArray(order.getDelivery());
                deliveryList = jsonArray.toJavaList(Delivery.class);
                for (Delivery deliveryNode : deliveryList) {
                    if (deliveryNode.getDeliveryNumber().equals(delivery.getDeliveryNumber())) {
                        isExist=true;
                        break;
                    }
                }
            }
            if(!isExist){
                deliveryList.add(delivery);
            }
            order.setDelivery(JSON.toJSONString(deliveryList));
            if(order.getState()==OrderState.COPY_SUCCESS.getValue()){
                order.setState(OrderState.GOOD_HAS_SEND.getValue());
                isFirst=true;
            }
            SpecialValue specialValue=specialValueMapper.selectOne(new QueryWrapper<>());
            order.setAutoFinishAt(DateUtils.getTimeAfterDay(specialValue.getOrderAutoFinish()));
            orderMapper.updateById(order);
            stringRedisTemplate.opsForValue().set(RedisHeader.ORDER_AUTO_FINISH.getHeader()+"__"+order.getId(), String.valueOf(new Date().getTime()),specialValue.getOrderAutoFinish(), TimeUnit.DAYS);
            if(isFirst){
                saleDataService.delivery(order);
                mailService.sendOrder(order);
            }
        }
    }


}
